import { Service } from 'egg';
import { Op } from 'sequelize';
import { RESULT_CODE } from '../utils/constants/code'

export default class ExclusiveRestaurantService extends Service {
  // 查询用户专属店
  async findExclusiveRestaurant(restaurant_id?:string) {
    const { ctx } = this;
    let userId = ctx.state.user.user_id;
    const existed = await ctx.model.ExclusiveRestaurantInvite.findOne({
      where: {
        restaurant_id: restaurant_id || 0,
        invitee_id: userId,
        status: { [Op.in]: ['accepted'] },
      },
    });
    if(existed) {
      userId = existed.inviter_id;
    }
    // 检查店名是否已存在
    const existingRestaurant:any = await ctx.model.ExclusiveRestaurant.findOne({
      where: { 
        user_id: userId,
      },
    });
    
    
    if (!existingRestaurant) {
      return null;
    }
    const restaurantData: any = existingRestaurant.toJSON ? existingRestaurant.toJSON() : existingRestaurant;
    restaurantData.imgList = restaurantData.pictures ? restaurantData.pictures.split(',').map((p: string) => ({ url: this.config.host + p, path: p })) : [];
    return restaurantData;
  }
  // 专属餐厅申请
  async addExclusiveRestaurant(data: any) {
    const { ctx } = this;
    const userId = ctx.state.user.user_id;

    // 检查店名是否已存在
    const existingRestaurant = await ctx.model.ExclusiveRestaurant.findOne({
      where: { 
        name: data.name,
        status: { [Op.in]: ['pending', 'approved'] }
      },
    });

    if (existingRestaurant) {
      ctx.throw(RESULT_CODE.FAIL, '店名已存在，请使用其他名称');
    }

    const restaurant = await ctx.model.ExclusiveRestaurant.create({
      ...data,
      user_id: userId,
      status: 'pending',
    });

    return restaurant;
  }

  // 更新专属餐厅信息（店名、介绍）
  async updateExclusiveRestaurant(data: any) {
    const { ctx } = this;
    const userId = ctx.state.user.user_id;

    // 查找用户当前餐厅
    const restaurant = await ctx.model.ExclusiveRestaurant.findOne({
      where: { user_id: userId },
    });

    if (!restaurant) {
      ctx.throw(RESULT_CODE.FAIL, '专属餐厅不存在');
    }
    const { status } = restaurant;
    await restaurant.update({ ...data, status });
    return restaurant;
  }

  async getApplicationList(params: any) {
    const { ctx } = this;
    const { page = 1, limit = 10, status } = params;
    const offset = (page - 1) * limit;

    const whereCondition: any = {};
    if (status) {
      whereCondition.status = status;
    }

    const { count, rows } = await ctx.model.ExclusiveRestaurant.findAndCountAll({
      where: whereCondition,
      order: [['created_at', 'DESC']],
      limit: parseInt(limit),
      offset,
      include: [
        {
          model: ctx.model.User,
          as: 'user',
          attributes: ['user_name', 'mobile'],
        },
      ],
    });


    // 处理标签数据
    const restaurants = rows.map(restaurant => {
      const restaurantData = restaurant!.toJSON() as any;
      if (restaurantData?.tags) {
        restaurantData.tagList = restaurantData?.tags.split(',').map(Number);
      }
      if(restaurantData.pictures) {
        restaurantData.imgList = restaurantData.pictures ? restaurantData.pictures.split(',').map(i => this.config.host + i) : [];
      }
      return restaurantData;
    });

    return {
      list: restaurants,
      total: count,
      page: parseInt(page),
      limit: parseInt(limit),
    };
  }

  async audit(id: number, status: 'approved' | 'rejected', remark?: string) {
    const { ctx } = this;

    const restaurant = await ctx.model.ExclusiveRestaurant.findByPk(id);
    if (!restaurant) {
      ctx.throw(RESULT_CODE.FAIL, '申请不存在');
    }

    // 更新状态，如果有备注也可以保存
    const updateData: any = { status };
    if (remark) {
      updateData.remark = remark;
    }

    await restaurant!.update(updateData);

    return { message: '审核完成' };
  }

  // 添加分类
  async addCategory(name: string, sort_order: number = 0, icon?: string) {
    const { ctx } = this;
    const userId = ctx.state.user.user_id;

    const restaurant = await ctx.model.ExclusiveRestaurant.findOne({
      where: { user_id: userId, status: 'approved' },
    });
    if (!restaurant) ctx.throw(RESULT_CODE.FAIL, '专属餐厅不存在或未通过审核');

    // 同餐厅分类重名校验
    const existed = await ctx.model.ExclusiveDishCategory.findOne({
      where: { restaurant_id: (restaurant as any).id, name },
    });
    if (existed) ctx.throw(RESULT_CODE.FAIL, '该分类已存在');

    const category = await ctx.model.ExclusiveDishCategory.create({
      restaurant_id: (restaurant as any).id,
      name,
      icon,
      sort_order,
    });

    return category;
  }

  // 删除分类（级联删除专属菜品，依赖外键或手动）
  async deleteCategory(categoryId: number) {
    const { ctx } = this;
    const userId = ctx.state.user.user_id;

    const restaurant = await ctx.model.ExclusiveRestaurant.findOne({
      where: { user_id: userId, status: 'approved' },
    });
    if (!restaurant) ctx.throw(RESULT_CODE.FAIL, '专属餐厅不存在或未通过审核');

    // 同分类菜品重名校验
    const existed = await ctx.model.ExclusiveDish.findOne({
      where: { category_id: categoryId },
    });
    if (existed) ctx.throw(RESULT_CODE.FAIL, '该分类有菜品不允许删除');

    const category = await ctx.model.ExclusiveDishCategory.findByPk(categoryId);
    if (!category) ctx.throw(RESULT_CODE.FAIL, '分类不存在');
    if ((category as any).restaurant_id !== (restaurant as any).id) ctx.throw(403, '无权删除该分类');

    await category.destroy();
    return { message: '删除成功' };
  }

  // 添加菜品（支持多图 pictures）
  async addDish(payload: { category_id: number; name: string; price?: number; description?: string; pictures?: string }) {
    const { ctx } = this;
    const userId = ctx.state.user.user_id;
    const { category_id, name, price, description, pictures } = payload;

    const restaurant = await ctx.model.ExclusiveRestaurant.findOne({
      where: { user_id: userId, status: 'approved' },
    });
    if (!restaurant) ctx.throw(RESULT_CODE.FAIL, '专属餐厅不存在或未通过审核');

    const category = await ctx.model.ExclusiveDishCategory.findByPk(category_id);
    if (!category) ctx.throw(RESULT_CODE.FAIL, '分类不存在');
    if ((category as any).restaurant_id !== (restaurant as any).id) ctx.throw(403, '无权在该分类下添加菜品');

    // 同分类菜品重名校验
    const existed = await ctx.model.ExclusiveDish.findOne({
      where: { category_id, name },
    });
    if (existed) ctx.throw(RESULT_CODE.FAIL, '该分类下菜品已存在');

    const dish = await ctx.model.ExclusiveDish.create({
      restaurant_id: (restaurant as any).id,
      category_id,
      name,
      pictures,
      price,
      description,
    });

    return dish;
  }

  // 删除菜品
  async deleteDish(dishId: number) {
    const { ctx } = this;
    const userId = ctx.state.user.user_id;

    const restaurant = await ctx.model.ExclusiveRestaurant.findOne({
      where: { user_id: userId, status: 'approved' },
    });
    if (!restaurant) ctx.throw(RESULT_CODE.FAIL, '专属餐厅不存在或未通过审核');

    const dish = await ctx.model.ExclusiveDish.findByPk(dishId);
    if (!dish) ctx.throw(RESULT_CODE.FAIL, '菜品不存在');
    if ((dish as any).restaurant_id !== (restaurant as any).id) ctx.throw(403, '无权删除该菜品');

    await dish.destroy();
    return { message: '删除成功' };
  }

  // 获取分类及分类下菜品列表
  async getCategoriesWithDishes(query:any) {
    const { ctx } = this;
    let userId = ctx.state.user.user_id;
    const { restaurant_id, filter_hide } = query;

    const existed = await ctx.model.ExclusiveRestaurantInvite.findOne({
      where: {
        restaurant_id,
        invitee_id: userId,
        status: { [Op.in]: ['accepted'] },
      },
    });

    if(existed) {
      userId = existed.inviter_id;
    }

    const restaurant = await ctx.model.ExclusiveRestaurant.findOne({
      where: { user_id: userId, status: 'approved' },
    });
    if (!restaurant && !existed) {
      if(!restaurant) ctx.throw(RESULT_CODE.FAIL, '专属餐厅不存在');
      if(!existed) ctx.throw(RESULT_CODE.FAIL, '您不是该餐厅的客户');
    }

    // 查询该餐厅的分类，并包含分类下的菜品
    const categories = await ctx.model.ExclusiveDishCategory.findAll({
      where: { restaurant_id: restaurant?.id },
      order: [['sort_order', 'ASC'], ['id', 'ASC']],
      include: [
        {
          model: ctx.model.ExclusiveDish,
          as: 'dishes',
          required: false,
          where: {
            restaurant_id: restaurant?.id,
            is_hide: filter_hide ? { [Op.in]: [0] } : { [Op.in]: [0, 1] },
          }
        },
      ],
    });

    // 序列化并补充图片绝对地址列表
    const list = categories.map((cat: any) => {
      const c = cat.toJSON ? cat.toJSON() : cat;
      c.dishes = (c.dishes || []).map((d: any) => {
        const pictures = d.pictures || '';
        const imgList = pictures ? pictures.split(',').map((p: string) => ({ url: this.config.host + p, path: p })) : [];
        return { ...d, imgList };
      });
      return c;
    });

    return list;
  }

  // 更新分类
  async updateCategory(payload: { id: number; name?: string; sort_order?: number, icon?: string}) {
    const { ctx } = this;
    const userId = ctx.state.user.user_id;
    const { id, name, sort_order, icon } = payload;

    const restaurant = await ctx.model.ExclusiveRestaurant.findOne({
      where: { user_id: userId, status: 'approved' },
    });
    if (!restaurant) ctx.throw(RESULT_CODE.FAIL, '专属餐厅不存在或未通过审核');

    const category = await ctx.model.ExclusiveDishCategory.findByPk(id);
    if (!category) ctx.throw(RESULT_CODE.FAIL, '分类不存在');
    if ((category as any).restaurant_id !== (restaurant as any).id) ctx.throw(403, '无权操作该分类');

    const updates: any = {};
    if (name !== undefined) {
      // 重名校验（同餐厅）
      const existed = await ctx.model.ExclusiveDishCategory.findOne({
        where: { restaurant_id: (restaurant as any).id, name, id: { [Op.ne]: id } },
      });
      if (existed) ctx.throw(RESULT_CODE.FAIL, '该分类名称已存在');
      updates.name = name;
    }
    if (sort_order !== undefined) {
      updates.sort_order = sort_order;
    }

    if(icon) {
      updates.icon = icon;
    }

    await (category as any).update(updates);
    return category;
  }

  // 更新菜品（可更新名称、价格、描述、图片、分类）
  async updateDish(payload: { id: number; name?: string; price?: number; description?: string; pictures?: string; category_id?: number; is_hide?: number; }) {
    const { ctx } = this;
    const userId = ctx.state.user.user_id;
    const { id, name, price, description, pictures, category_id, is_hide } = payload;

    const restaurant = await ctx.model.ExclusiveRestaurant.findOne({
      where: { user_id: userId, status: 'approved' },
    });
    if (!restaurant) ctx.throw(RESULT_CODE.FAIL, '专属餐厅不存在或未通过审核');

    const dish = await ctx.model.ExclusiveDish.findByPk(id);
    if (!dish) ctx.throw(RESULT_CODE.FAIL, '菜品不存在');
    if ((dish as any).restaurant_id !== (restaurant as any).id) ctx.throw(403, '无权操作该菜品');

    const updates: any = {};
    // 分类变更校验
    let targetCategoryId = (dish as any).category_id;
    if (category_id !== undefined) {
      const category = await ctx.model.ExclusiveDishCategory.findByPk(category_id);
      if (!category) ctx.throw(RESULT_CODE.FAIL, '分类不存在');
      if ((category as any).restaurant_id !== (restaurant as any).id) ctx.throw(403, '无权使用该分类');
      targetCategoryId = category_id;
      updates.category_id = category_id;
    }

    // 重名校验（在目标分类内）
    const finalName = name !== undefined ? name : (dish as any).name;
    const existed = await ctx.model.ExclusiveDish.findOne({
      where: { category_id: targetCategoryId, name: finalName, id: { [Op.ne]: id } },
    });
    if (existed) ctx.throw(RESULT_CODE.FAIL, '该分类下菜品名称已存在');

    updates.is_hide = is_hide;
    if (name !== undefined) updates.name = name;
    if (price !== undefined) updates.price = price;
    if (description !== undefined) updates.description = description;
    if (pictures !== undefined) updates.pictures = pictures;

    await (dish as any).update(updates);
    return dish;
  }
}